package org.apache.cordova.sharesdk;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
//import cn.sharesdk.framework.TitleLayout;
//import cn.sharesdk.framework.utils.UIHandler;

//import cn.sharesdk.wechat.utils.WXMediaMessage.IMediaObject;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;
import android.content.Context;
import android.util.Log;
//import android.widget.Toast;
//import android.os.Looper;

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;

public class ShareSdkPlugin extends CordovaPlugin {

    public static final String TAG = "org.apache.cordova.sharesdk";

    @Override
    public boolean execute(final String action, final JSONArray data, final CallbackContext callbackContext) throws JSONException {
        if (TextUtils.isEmpty(action)) {
            callbackContext.error("method[" + action + "] isEmpty!");
            return false;
        }

        final Context context = cordova.getActivity().getApplicationContext();
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Method method = ShareSdkPlugin.class.getDeclaredMethod(action, JSONArray.class, CallbackContext.class, Context.class);
                    method.invoke(ShareSdkPlugin.this, data, callbackContext, context);
                    Log.v(TAG, action + ": " + data.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    callbackContext.error(e.getMessage());
                }
            }
        };

        if ("initSDK".equals(action)) {
            cordova.getActivity().runOnUiThread(runnable);
        } else {
            //if (Looper.myLooper() == null) {
            //    Looper.prepare();
            //}
            cordova.getThreadPool().execute(runnable);
        }
        return true;
    }

    /**
     * initSDK
     *
     * @param data
     * @param callbackContext
     * @param Context
     */
    void initSDK(JSONArray data, CallbackContext callbackContext, Context context) {
        try {
            ShareSDK.initSDK(cordova.getActivity());
            callbackContext.success();
        } catch (Exception e) {
            e.printStackTrace();
            callbackContext.error(e.getMessage());
        }
    }

    /**
     * share
     *
     * @param data
     * @param callbackContext
     * @param Context
     */
    void share(JSONArray data, final CallbackContext callbackContext, final Context context) {
        try {
            final String platName = data.getString(0);
            final JSONObject args = data.getJSONObject(1);
            ShareParams shareParams = getShareParams(args);

            Platform platform = ShareSDK.getPlatform(platName);
            platform.setPlatformActionListener(new PlatformActionListener() {

                @Override
                public void onError(Platform platform, int action, Throwable th) {
                    th.printStackTrace();
                    try {
                        JSONObject msg = new JSONObject();
                        msg.put("name", "onError");
                        msg.put("platform", String.valueOf(((Platform) platform).getName()));
                        msg.put("action", action);
                        callbackContext.error(msg.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                        callbackContext.error(e.getMessage());
                    }
                }

                @Override
                public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
                    //通过platform.getDb().getUserId();
                    //platform.getDb().getUserName();等等来获取用户信息
                    try {
                        JSONObject msg = new JSONObject();
                        msg.put("name", "onComplete");
                        msg.put("platform", String.valueOf(((Platform) platform).getName()));
                        msg.put("action", action);
                        callbackContext.success(msg.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                        callbackContext.error(e.getMessage());
                    }
                }

                @Override
                public void onCancel(Platform platform, int action) {
                    try {
                        JSONObject msg = new JSONObject();
                        msg.put("name", "onCancel");
                        msg.put("platform", String.valueOf(((Platform) platform).getName()));
                        msg.put("action", action);
                        callbackContext.error(msg.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                        callbackContext.error(e.getMessage());
                    }
                }
            }); // 设置分享事件回调
            //执行图文分享
            platform.share(shareParams);
            //callbackContext.success(toString);
        } catch (JSONException e) {
            e.printStackTrace();
            callbackContext.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            callbackContext.error(e.getMessage());
        }
    }

    /**
     * getShareParams
     *
     * @param JSONObject args
     * @return ShareParams
     */
    private ShareParams getShareParams(JSONObject args) throws JSONException {
        /* 微信
         public static final int TYPE_APPDATA = 7;
         public static final int TYPE_EMOJI = 8;
         public static final int TYPE_FILE = 6;
         public static final int TYPE_IMAGE = 2;
         public static final int TYPE_MUSIC = 3;
         public static final int TYPE_TEXT = 1;
         public static final int TYPE_UNKNOWN = 0;
         public static final int TYPE_URL = 5;
         public static final int TYPE_VIDEO = 4;
         */

        /*
         protected static final String TEXT = "text";
         protected static final String IMAGE_PATH = "imagePath";
         protected static final String FILE_PATH = "filePath";
         protected static final String TITLE = "title";
         protected static final String NOTEBOOK = "notebook";
         protected static final String STACK = "stack";
         protected static final String TAGS = "tags";
         protected static final String IS_PUBLIC = "isPublic";
         protected static final String IS_FRIEND = "isFriend";
         protected static final String IS_FAMILY = "isFamily";
         protected static final String SAFETY_LEVEL = "safetyLevel";
         protected static final String CONTENT_TYPE = "contentType";
         protected static final String HIDDEN = "hidden";
         protected static final String VENUE_NAME = "venueName";
         protected static final String VENUE_DESCRIPTION = "venueDescription";
         protected static final String LATITUDE = "latitude";
         protected static final String LONGITUDE = "longitude";
         protected static final String IMAGE_URL = "imageUrl";
         protected static final String COMMENT = "comment";
         protected static final String TITLE_URL = "titleUrl";
         protected static final String URL = "url";
         protected static final String ADDRESS = "address";
         protected static final String SITE = "site";
         protected static final String SITE_URL = "siteUrl";
         protected static final String GROPU_ID = "gropuId";
         protected static final String EXT_INFO = "extInfo";
         protected static final String SHARE_TYPE = "shareType";
         protected static final String MUSIC_URL = "musicUrl";
         protected static final String IMAGE_DATA = "imageData";
         protected static final String AUTHOR = "author";
         protected static final String SCENCE = "scene";
         protected static final String CUSTOM_FLAG = "customFlag";
         protected static final String EXECUTE_URL = "executeUrl";
         protected static final String INSTALL_URL = "installUrl";
         protected static final String IS_SHARE_TENCENT_WEIBO = "isShareTencentWeibo";
         protected static final String IMAGE_ARRAY = "imageArray";
         */
        ShareParams shareParams = new ShareParams();

        for (Iterator iter = args.keys(); iter.hasNext();) {
            String key = (String) iter.next();
            shareParams.set(key, args.get(key));
        }
        /*
         //text是分享文本，所有平台都需要这个字段
         String text = args.getString("text");
         if (!TextUtils.isEmpty(text)) {
         shareParams.setText(text);
         }

         //分享时Notification的图标和文字
         String notification = args.getString("notification");
         if (!TextUtils.isEmpty(notification)) {
         shareParams.setNotification(notification);
         }

         String image = args.getString("image");
         if (!TextUtils.isEmpty(image)) {
         shareParams.setImage(image);
         }

         String latitude = args.getString("latitude");
         if (!TextUtils.isEmpty(latitude)) {
         shareParams.setLatitude(latitude);
         }

         String longitude = args.getString("longitude");
         if (!TextUtils.isEmpty(longitude)) {
         shareParams.setLongitude(longitude);
         }
         //title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
         String title = args.getString("title");
         if (!TextUtils.isEmpty(title)) {
         shareParams.setTitle(title);
         }

         //titleUrl是标题的网络链接，仅在人人网和QQ空间使用
         String titleUrl = args.getString("titleUrl");
         if (!TextUtils.isEmpty(titleUrl)) {
         shareParams.setTitleUrl(titleUrl);
         }

         String imageData = args.getString("imageData");
         if (!TextUtils.isEmpty(imageData)) {
         shareParams.setImageData(imageData);
         }

         //imagePath是图片的本地路径
         String imagePath = args.getString("imagePath");
         if (!TextUtils.isEmpty(imagePath)) {
         shareParams.setImagePath(imagePath);
         }

         //网络图片
         String imageUrl = args.getString("imageUrl");
         if (!TextUtils.isEmpty(imageUrl)) {
         shareParams.setImageUrl(imageUrl);
         }

         //网络音乐
         String musicUrl = args.getString("musicUrl");
         if (!TextUtils.isEmpty(musicUrl)) {
         shareParams.setMusicUrl(musicUrl);
         }

         //url仅在微信
         String url = args.getString("url");
         if (!TextUtils.isEmpty(url)) {
         shareParams.setUrl(url);
         }

         String shareType = args.getInt("shareType");
         if (shareType) {
         shareParams.setShareType(shareType);
         }

         //comment是我对这条分享的评论，仅在人人网和QQ空间使用
         String comment = args.getString("comment");
         if (!TextUtils.isEmpty(comment)) {
         shareParams.setComment(comment);
         }

         //siteUrl是分享此内容的网站地址，仅在QQ空间使用
         String siteurl = args.getString("siteurl");
         if (!TextUtils.isEmpty(siteurl)) {
         shareParams.setSiteUrl(siteurl);
         }

         //site是分享此内容的网站名称，仅在QQ空间使用
         String site = args.getString("site");
         if (!TextUtils.isEmpty(site)) {
         shareParams.setSite(site);
         }

         String filepath = args.getString("filepath");
         if (!TextUtils.isEmpty(filepath)) {
         shareParams.setFilePath(filepath);
         }

         String extinfo = args.getString("extinfo");
         if (!TextUtils.isEmpty(extinfo)) {
         shareParams.setExtInfo(extinfo);
         }
         */
        return shareParams;
    }

    /**
     * wechat test
     *
     * @param data
     * @param callbackContext
     * @param Context
     */
    void wechat(JSONArray data, final CallbackContext callbackContext, final Context context) {
        try {
            ShareParams shareParams = new ShareParams();
            shareParams.setTitle("setTitle");
            shareParams.setText("setText");
            shareParams.setShareType(1);

            Platform weibo = ShareSDK.getPlatform("WechatMoments");
            weibo.setPlatformActionListener(new PlatformActionListener() {

                @Override
                public void onError(Platform platform, int action, Throwable th) {
                    th.printStackTrace();
                    String toString = new StringBuilder(String.valueOf(((Platform) platform).getName())).append(" onError: ").append(action).toString();
                    callbackContext.error(toString);
                }

                @Override
                public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
                    //通过platform.getDb().getUserId();
                    //platform.getDb().getUserName();等等来获取用户信息
                    String toString = new StringBuilder(String.valueOf(((Platform) platform).getName())).append(" onComplete: ").append(action).toString();
                    callbackContext.success(toString);
                }

                @Override
                public void onCancel(Platform platform, int action) {
                    String toString = new StringBuilder(String.valueOf(((Platform) platform).getName())).append(" onCancel: ").append(action).toString();
                    callbackContext.error(toString);
                }
            }); // 设置分享事件回调
            //执行图文分享
            weibo.share(shareParams);

            //callbackContext.success(toString);
        } catch (Exception e) {
            e.printStackTrace();
            callbackContext.error(e.getMessage());
        }
    }
}
